Page({
  data: {
    currentLevel: 1,
    unlockedLevel: 1,
    score: 0,
    currentWord: {
      english: 'HELLO',
      chinese: '喂、你好'
    },
    userAnswer: '',
    shuffledLetters: ['H', 'E', 'L', 'L', 'O'],
    wordList: [
      { english: 'HELLO', chinese: '喂、你好' },
      { english: 'MONKEY', chinese: '猴子、顽童' },
      { english: 'PANDA', chinese: '大熊猫' },
      { english: 'TEDDY BEAR', chinese: '玩具熊' }
    ],
    isShaking: false,
    dictType: 'course',
    grade3Expanded: false,
    grade4Expanded: false,
    starterExpanded: false,
    courseDict: {
      grade3: {
        name: '三年级',
        progress: 0,
        lessons: Array(8).fill().map((_, i) => ({
          id: i + 1,
          name: `第${i + 1}课`,
          completed: false
        }))
      },
      grade4: {
        name: '四年级',
        progress: 0,
        lessons: Array(8).fill().map((_, i) => ({
          id: i + 1,
          name: `第${i + 1}课`,
          completed: false
        }))
      }
    },
    cambridgeDict: {
      starter: {
        name: '预备级',
        progress: 0,
        semesters: {
          1: Array(16).fill().map((_, i) => ({
            id: i + 1,
            name: `第${i + 1}单元`,
            completed: false
          })),
          2: Array(16).fill().map((_, i) => ({
            id: i + 1,
            name: `第${i + 1}单元`,
            completed: false
          }))
        }
      }
    }
  },

  onLoad() {
    const firstWord = this.data.wordList[0];
    const letters = this.generateLetters(firstWord.english);

    this.setData({
      currentWord: firstWord,
      shuffledLetters: letters
    });
  },

  initLevel(level) {
    if (level > this.data.wordList.length) {
      wx.showToast({
        title: '已完成所有单词！',
        icon: 'success'
      });
      return;
    }

    const word = this.data.wordList[level - 1];
    const letters = this.generateLetters(word.english);

    this.setData({
      currentLevel: level,
      currentWord: word,
      userAnswer: '',
      shuffledLetters: letters
    });
  },

  selectLetter(e) {
    this.playSound('click')
    const letter = e.currentTarget.dataset.letter;
    if (this.data.userAnswer.length < this.data.currentWord.english.length) {
      const newAnswer = this.data.userAnswer + letter;
      this.setData({
        userAnswer: newAnswer
      });

      if (newAnswer.length === this.data.currentWord.english.length) {
        this.checkAnswer(newAnswer);
      }
    }
  },

  resetAnswer() {
    const currentAnswer = this.data.userAnswer;
    if (currentAnswer.length > 0) {
      this.setData({
        userAnswer: currentAnswer.slice(0, -1)
      });
    }
  },

  resetAll() {
    this.playSound('click')
    this.setData({
      userAnswer: ''
    });
  },

  confirmAnswer() {
    if (this.data.userAnswer === this.data.currentWord.english) {
      this.playSound('correct')  // 添加正确音效
      let newScore = this.data.score + 10;
      let newUnlockedLevel = Math.max(this.data.unlockedLevel, this.data.currentLevel + 1);

      this.setData({
        score: newScore,
        unlockedLevel: newUnlockedLevel
      });

      wx.showToast({
        title: '回答正确！',
        icon: 'success'
      });

      // 延迟进入下一关
      setTimeout(() => {
        if (this.data.currentLevel < 20) {
          this.initLevel(this.data.currentLevel + 1);
        }
      }, 1500);
    } else {
      this.playSound('wrong')  // 添加错误音效
      this.setData({ isShaking: true })  // 触发抖动动画

      setTimeout(() => {
        this.setData({ isShaking: false })
      }, 500)

      wx.showToast({
        title: '再试一次',
        icon: 'error'
      });
      this.resetAnswer();
    }
  },

  selectLevel(e) {
    const level = e.currentTarget.dataset.level;
    if (level <= this.data.unlockedLevel) {
      this.initLevel(level);
    }
  },

  shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
  },

  // 播放音效
  playSound(type) {
    const audio = wx.createInnerAudioContext()

    switch (type) {
      case 'click':
        audio.src = '/audio/select03 (1).mp3'
        break
      case 'correct':
        audio.src = '/audio/correct.mp3'
        break
      case 'wrong':
        audio.src = '/audio/wrong.mp3'
        break
    }

    audio.play()

    // 播放完成后释放资源
    audio.onEnded(() => {
      audio.destroy()
    })
  },

  checkAnswer(answer) {
    if (answer === this.data.currentWord.english) {
      this.playSound('correct')
      let newScore = this.data.score + 2;
      let newUnlockedLevel = Math.max(this.data.unlockedLevel, this.data.currentLevel + 1);

      this.setData({
        score: newScore,
        unlockedLevel: newUnlockedLevel
      });

      // 每过一关加2积分
      getApp().addScore(2, 'word_challenge');

      if (this.data.currentLevel === this.data.wordList.length) {
        wx.showToast({
          title: '恭喜完成本单元！',
          icon: 'success',
          duration: 2000
        });
      } else {
        wx.showToast({
          title: '+2积分',
          icon: 'success',
          duration: 1000
        });
      }

      setTimeout(() => {
        if (this.data.currentLevel < this.data.wordList.length) {
          this.initLevel(this.data.currentLevel + 1);
        }
      }, 1500);
    } else {
      this.playSound('wrong')
      this.setData({ isShaking: true })

      setTimeout(() => {
        this.setData({ isShaking: false })
      }, 500)

      wx.showToast({
        title: '再试一次',
        icon: 'error'
      });
      this.resetAnswer();
    }
  },

  onUnload() {
    // 页面卸载时停止背景音乐
    if (this.bgm) {
      this.bgm.stop();
    }
  },

  // 切换词库类型
  handleSwitchType(e) {
    const { type } = e.detail;
    this.setData({ dictType: type });
  },

  // 选择课程
  handleSelectLesson(e) {
    const { grade, lesson } = e.detail;
    this.loadLessonWords(grade, lesson);
  },

  // 选择单元
  handleSelectUnit(e) {
    const { level, semester, unit } = e.detail;
    this.loadUnitWords(level, semester, unit);
  },

  // 加载课程词库的单词数据
  loadLessonWords(grade, lesson) {
    wx.showLoading({
      title: '加载中...'
    });

    // 模拟加载数据
    setTimeout(() => {
      wx.hideLoading();
      // 这里应该是实际的数据加载逻辑
      this.setData({
        currentGroup: 0,
        currentWordIndex: 0,
        // 加载新的单词组数据
        wordGroups: []  // 这里需要设置实际的单词数据
      });
    }, 500);
  },

  // 加载剑桥词库的单词数据
  loadUnitWords(level, semester, unit) {
    wx.showLoading({
      title: '加载中...'
    });

    // 模拟加载数据
    setTimeout(() => {
      wx.hideLoading();
      // 这里应该是实际的数据加载逻辑
      this.setData({
        currentGroup: 0,
        currentWordIndex: 0,
        // 加载新的单词组数据
        wordGroups: []  // 这里需要设置实际的单词数据
      });
    }, 500);
  },

  // 生成字母选择区的字母
  generateLetters(word) {
    let letters = word.split('');
    // 添加一些干扰字母
    const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    while (letters.length < 12) {  // 确保有足够的字母选
      const randomLetter = alphabet[Math.floor(Math.random() * alphabet.length)];
      if (!letters.includes(randomLetter)) {
        letters.push(randomLetter);
      }
    }
    // 打乱字母顺序
    return this.shuffleArray(letters);
  }
}); 